package org.jeecg.modules.demo.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.crm.dto.UserInfoDTO;
import org.jeecg.modules.demo.crm.entity.CAdditionalRequest;
import org.jeecg.modules.demo.crm.entity.CWxMsg;
import org.jeecg.modules.demo.crm.mapper.CAdditionalRequestMapper;
import org.jeecg.modules.demo.crm.mapper.CWxMsgMapper;
import org.jeecg.modules.demo.crm.service.ICWxMsgService;
import org.jeecg.modules.demo.crm.wxmsg.TemplateMsgServer;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 微信模版消息发送记录
 * @Author: jeecg-boot
 * @Date:   2025-07-26
 * @Version: V1.0
 */
@Service
public class CWxMsgServiceImpl extends ServiceImpl<CWxMsgMapper, CWxMsg> implements ICWxMsgService {

    @Autowired
    TemplateMsgServer templateMsgServer;

    @Autowired
    CAdditionalRequestMapper additionalRequestMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    CWxMsgMapper cWxMsgMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public void sendDemo() {
        JSONObject body = new JSONObject();
        body.put("character_string13","W86577567");
        body.put("thing44","XXX单位电脑更换硬盘");
        body.put("short_thing5","已分配");
        body.put("thing27","李四");
        body.put("thing35","您有任务工单已审核通过，");
        try {
            Result res = templateMsgServer.send("oMw6fvsJnq5cNd8Z_YH6_4Bnp590",
                    "r6oAmS2Yt2Ai71dobqJD-Kh8KMoHBPTl3LAMRNd3xN8", "", body);
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public void gather() {
        String prefix = "wxMsg:";
        //用户新提交的需求 提醒
        List<CAdditionalRequest> additionalRequestList = additionalRequestMapper.findByStatus("待处理");
        List<UserInfoDTO> userList = cWxMsgMapper.queryByOpenId("项目负责人");
        if(userList != null && userList.size() > 0){
            for (CAdditionalRequest additionalRequest : additionalRequestList) {
                String dataKey = prefix + Md5Util.md5Encode(prefix + "-" + additionalRequest.getId() + " - " + additionalRequest.getStatus(),"utf-8");
                if(redisUtil.hasKey(dataKey) == false){
                    for (UserInfoDTO userInfoDTO : userList) {
                        CWxMsg cwxMsg = new CWxMsg();
                        cwxMsg.setStatus("待发送");
                        cwxMsg.setUserId(userInfoDTO.getId());
                        cwxMsg.setOpenId(userInfoDTO.getOpenId());
                        cwxMsg.setTemplateId("r6oAmS2Yt2Ai71dobqJD-Kh8KMoHBPTl3LAMRNd3xN8");
                        cwxMsg.setBusiness("需求新增成功");

                        String thing44 = additionalRequest.getTitle();
                        if (thing44 != null && thing44.length() > 17) {
                            thing44 = thing44.substring(0, 17) + "...";
                        }
                        String thing35 = additionalRequest.getApplicationReason();
                        if (thing35 != null && thing35.length() > 17) {
                            thing35 = thing35.substring(0, 17) + "...";
                        }
                        String character_string13 = additionalRequest.getProjectNumber();
                        if (character_string13 != null && character_string13.length() > 29) {
                            character_string13 = character_string13.substring(0, 29) + "...";
                        }
                        String thing27 = "";
                        SysUser sysUser = sysUserMapper.selectById(additionalRequest.getUserId());
                        if(sysUser != null){
                            thing27 = sysUser.getUsername();
                        }


                        JSONObject body = new JSONObject();
                        body.put("character_string13",character_string13);
                        body.put("thing44",thing44);
                        body.put("short_thing5",additionalRequest.getStatus());
                        body.put("thing27",thing27);
                        body.put("thing35",thing35);
                        cwxMsg.setData(JSONObject.toJSONString(body));
                        cWxMsgMapper.insert(cwxMsg);
                        //第一次发送
                        redisUtil.set(dataKey,additionalRequest.getId(),86400);//一天后过期
                    }

                }

            }
        }else {
            throw new RuntimeException("系统未设置--项目负责人,无法推送消息");
        }

    }

    @Override
    public void send() {
        List<CWxMsg> msgList = cWxMsgMapper.findByPending();
        for (CWxMsg cWxMsg : msgList) {
            try {
                String data = cWxMsg.getData();
                JSONObject body = JSONObject.parseObject(data);
                Result res = templateMsgServer.send(cWxMsg.getOpenId(),
                        cWxMsg.getTemplateId(), cWxMsg.getUrl(), body);
                if (res.isSuccess()){
                    cWxMsg.setStatus("完成");
                }else {
                    cWxMsg.setStatus("失败");
                }
                cWxMsg.setSendTime(new Date());
                cWxMsg.setMsg(res.getMessage());
                cWxMsgMapper.updateById(cWxMsg);
            } catch (Exception e) {
                cWxMsg.setStatus("失败");
                cWxMsg.setSendTime(new Date());
                cWxMsg.setMsg(e.getMessage());
                cWxMsgMapper.updateById(cWxMsg);
            }
        }
    }
}
